package com.jufanshare.tokenjwt.conf;

import com.alibaba.fastjson.JSON;
import com.jufanshare.tokenjwt.common.enums.ErrorCodeEnum;
import com.jufanshare.tokenjwt.common.jwt.JwtRefreshSingle;
import com.jufanshare.tokenjwt.common.jwt.JwtUtils;
import com.jufanshare.tokenjwt.common.jwt.JwtValues;
import com.jufanshare.tokenjwt.common.result.Result;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;


public class JwtInterceptor extends HandlerInterceptorAdapter {
    public static final String USER_INFO_KEY = "user_info_key";

    @Autowired
    private JwtUtils jwtUtils;

    @Autowired
    private JwtValues jwtValues;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取用户请求token
        String token = request.getHeader(jwtUtils.getHeaderKey());
        if (StringUtils.isBlank(token)) {
            token = request.getParameter(jwtUtils.getHeaderKey());
        }
        if (StringUtils.isBlank(token)) {
            this.writerErrorMsg(ErrorCodeEnum.ILLEGAL_REQUEST.getCode(),
                    jwtUtils.getHeaderKey() + "不能为空",
                    response);
            return false;
        }
        response.setHeader("token",token);
        //校验并解析token，如果token过期或者篡改，则会返回null
        Claims claims = jwtUtils.verifyAndGetClaimsByToken(token);

        Map<String, Object> stringObjectMap = JwtRefreshSingle.getInstance().get(token);
        if(null == stringObjectMap){
            this.writerErrorMsg(ErrorCodeEnum.ILLEGAL_REQUEST.getCode(),
                    jwtUtils.getHeaderKey() + "无效，请重新登录",
                    response);
            response.setHeader("token","");
            return false;
        }

        if (null == claims) {
            //判断是否属于长时间没有请求导致token过期
            long expireTime = (long)stringObjectMap.get("expire");
            if(expireTime<System.currentTimeMillis()){
                this.writerErrorMsg(ErrorCodeEnum.ILLEGAL_REQUEST.getCode(),
                        jwtUtils.getHeaderKey() + "长时间未刷新登录过期，请重新登录",
                        response);
                //登录状态到期，移除token
                response.setHeader("token","");
                JwtRefreshSingle.getInstance().remove(token);
                return false;
            }
            //刷新登录状态过期时间
            stringObjectMap.put("expire",System.currentTimeMillis() + jwtValues.getTokenLogout() * 1000);

            //重新生成token
            String newToken = jwtUtils.generateToken(stringObjectMap);
            //刷新后token存入header返回
            response.setHeader("token",newToken);

            //新的token保存起来
            JwtRefreshSingle.getInstance().put(newToken,stringObjectMap);
            return false;
        }
        //校验通过后，设置用户信息到请求request里，在最终controller接口可以通过request取出这个对象
        request.setAttribute(USER_INFO_KEY, claims);
        return true;
    }

    /**
     * 错误信息json返回
     * @param code
     * @param msg
     * @param response
     * @throws IOException
     */
    private void writerErrorMsg(Integer code, String msg, HttpServletResponse response) throws IOException {
        Result result = new Result();
        result.code(code);
        result.setMsg(msg);
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().write(JSON.toJSONString(result));
    }
}
